package com.example.anquan.Service;


import com.example.anquan.guanli.Article;
import com.example.anquan.guanli.Comment;
import com.example.anquan.repository.ArticleRepository;
import com.example.anquan.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;


@Service
public class ArticleService {
    @Autowired
    private ArticleRepository articleRepository;
    @Autowired
    private CommentRepository commentRepository;
    //分页展示

    public Page<Article> pageArticle(int page, int size){
        Pageable pageable = PageRequest.of(page, size);
        return articleRepository.findAll(pageable);
    }

    public Article findArticleById(Integer id){
        if (articleRepository.findById(id).isPresent()) {
            return articleRepository.findById(id).get();
        }
        else {
            return null;
        }
    }
    public List<Article> findAll(){
        return articleRepository.findAll();
    }

    public void deleteById(Integer id){
        Article article = findArticleById(id);
        commentRepository.deleteByArticle(article);
    }
    //修改文章
    public void updateArticleById(Integer id, String title, String category,
                                  String content){
        Article article = findArticleById(id);
        article.setTitle(title);
        article.setCategory(category);
        article.setContent(content);
        articleRepository.save(article);
    }
    //新增文章
    public Article addArticle(String title, String category, String content){
        Article article = new Article();
        article.setTitle(title);
        article.setCategory(category);
        article.setContent(content);
        article.setDate(new Date());
        return articleRepository.save(article);
    }
}

